from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session

from app.crud import article as crud_article
from app.schemas.article import Article, ArticleCreate, ArticleUpdate
from app.db.session import get_db

router = APIRouter()

# 获取文章列表
@router.get("/", response_model=List[Article])
def read_articles(
    db: Session = Depends(get_db),
    skip: int = 0,
    limit: int = 10,
    status: Optional[str] = Query(None, description="文章状态：draft/published")
):
    """
    获取文章列表
    """
    articles = crud_article.get_articles(db, skip=skip, limit=limit, status=status)
    return articles

# 创建新文章
@router.post("/", response_model=Article)
def create_article(
    *,
    db: Session = Depends(get_db),
    article_in: ArticleCreate
):
    """
    创建新文章
    """
    # 打印接收到的标签信息
    print(f"接收到的标签IDs: {article_in.tags}")
    article = crud_article.create_article(db=db, article=article_in)
    # 打印创建后的标签信息
    print(f"创建后的标签数量: {len(article.tags)}")
    return article

# 获取指定文章详情
@router.get("/{article_id}", response_model=Article)
def read_article(
    *,
    db: Session = Depends(get_db),
    article_id: int
):
    """
    获取指定文章详情
    """
    article = crud_article.get_article(db=db, article_id=article_id)
    if not article:
        raise HTTPException(status_code=404, detail="文章不存在")
    # 增加浏览次数
    crud_article.increment_view_count(db=db, article_id=article_id)
    return article

# 更新文章
@router.put("/{article_id}", response_model=Article)
def update_article(
    *,
    db: Session = Depends(get_db),
    article_id: int,
    article_in: ArticleUpdate
):
    """
    更新文章
    """
    # 打印接收到的标签信息
    print(f"更新接收到的标签IDs: {article_in.tags}")
    article = crud_article.update_article(db=db, article_id=article_id, article=article_in)
    if not article:
        raise HTTPException(status_code=404, detail="文章不存在")
    # 打印更新后的标签信息
    print(f"更新后的标签数量: {len(article.tags)}")
    return article

# 删除文章
@router.delete("/{article_id}")
def delete_article(
    *,
    db: Session = Depends(get_db),
    article_id: int
):
    """
    删除文章（软删除）
    """
    success = crud_article.delete_article(db=db, article_id=article_id)
    if not success:
        raise HTTPException(status_code=404, detail="文章不存在")
    return {"message": "文章已删除"} 

# 获取所有草稿文章

# TODO: 分页功能没有具体实现
@router.get("/draft/", response_model=List[Article])
def get_draft_articles(
    db: Session = Depends(get_db),
    skip: int = 0,
    limit: int = 10
):
    return crud_article.get_articles(db, skip=skip, limit=limit, status="draft")

# 获取所有已发布文章
@router.get("/published/", response_model=List[Article])
def get_published_articles(
    db: Session = Depends(get_db),
    skip: int = 0,
    limit: int = 10
):
    return crud_article.get_articles(db, skip=skip, limit=limit, status="published")